import json
import time
import os
import sys

import requests

from core.browser_manager import BrowserManager as BM
from core.task_executor import TaskExecutor as TE
from core.baidu_cuttlefish import BaiduCuttlefish as BC
from core.api_client import ApiClient as AC
from bin.generate_article_thread_api import create_articles
from bin.login_manager import add_account
# 设置基础目录
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)


class WenkuManager:
	def __init__(self):
		"""初始化WenkuManager实例"""
		self.uid = None
		self.token = None
		self.ac = AC()
		self.account_list = []
		self.bot_list = []
		self.driver = None
		self.generate_model_list=[]
		self._login()
		self._set_infos()

	def _login(self):
		while True:
			username = str(input("请输入账号：")).strip()
			password = str(input("请输入密码：")).strip()
			data = {"username": username, "password": password, "timeout": 36000}
			# data = {'username': username, 'password': password, 'timeout': 36000}
			if not username or not password:
				print("请重新输入")
				continue
			token = requests.post("http://101.126.16.255/api/v1/login",data=data).json()
			# print(token)
			if int(token['code']):
				print(token['msg'])
				continue
			self.token = token['token']
			self.ac.token = self.token
			user_info = self.ac.get_data(endpoint="/api/wenku/user/get_user_info", username = username)
			# print(user_info)
			self.uid = user_info['id']
			break


	def _set_infos(self):
		"""登录并获取账号和机器人列表"""
		if self.uid:
			self.account_list = self.ac.get_data(endpoint="/api/wenku/account/get_accounts_list", user_id=self.uid)
			self.bot_list = self.ac.get_data(endpoint="/api/wenku/coze_bot/get_coze_list")
			self.generate_model_list = self.ac.get_data(endpoint="/api/wenku/coze_bot/get_generate_model")
			print(f"------已获取到{len(self.account_list)}个账号------")
		else:
			exit()

	def account_management(self):
		"""处理账号管理选项-11、更新cookie(未做)"""
		lever_2 = int(input("""
-10、登录查看
-12、更新账号信息
-99、返回
请输入对应的数字：
        """))

		if lever_2 == 10:
			self.view_login()
		# elif lever_2 == 11:
		# 	self.update_cookies()
		elif lever_2 == 12:
			self.update_infos()
	def view_login(self):
		"""登录查看账号"""
		options = [(i + 1, account['uname']) for i, account in enumerate(self.account_list)]
		for index, name in options:
			print(f"{index}、{name}")

		choice = input("请选择要操作的账号（输入序号）: ")
		try:
			choice = int(choice) - 1
			if 0 <= choice < len(self.account_list):
				bm = BM(cookie=self.account_list[choice]['cookie'], is_headless=0, target_type=1)
				self.driver = bm.driver
				while True:
					if int(input("请输入1关闭浏览器：")) == 1:
						self.driver = None
						bm = None
						break
			else:
				print("无效的选项，请重新选择。")
		except ValueError:
			print("请输入一个有效的数字序号。")

	def update_infos(self):
		for item in self.account_list:
			# 示例代码，实际代码需要补全
			bc = BC(item['cookie'])
			bc.get_all_info()
			user_info = bc.user_info
			# print(user_info)
			# print(type(user_info))
			print(f"========开始更新账号<{item['uname']}>========")
			self.ac.post_data(endpoint="/api/wenku/account/updateByCond", data=user_info)
			print(f"========账号<{item['uname']}>更新完成========")
			time.sleep(10)

	def update_cookies(self):
		"""更新账号cookie"""
		pass

	def generate_articles(self):
		"""处理文章生成选项"""
		lever_2 = int(input("""
-21、生成原力任务文章，从数据库获取标题自动生成(做任务用的)
-22、输入标题生成文章
-99、返回
请输入对应的数字：
        """))

		if lever_2 == 21:
			self.generate_task_articles()
		elif lever_2 == 22:
			self.generate_custom_articles()

	def generate_task_articles(self):
		"""从数据库获取标题并生成文章,只写英文的"""
		title_list = self.ac.get_data(endpoint="/api/wenku/titles/get_titles_list", ai_score=10, period=20240715)
		print(f"------已获取到{len(title_list)}个10分的写作任务------")
		task_list = [item['article_name'] for item in title_list]
		model = self.generate_model_list[1]
		output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'doc_files', 'task_files')
		create_articles(task_list, self.bot_list, output_dir=output_dir,model=model)

	def generate_custom_articles(self):
		"""根据用户输入生成文章"""
		options = [(i + 1, model['name']) for i, model in enumerate(self.generate_model_list)]
		for index, name in options:
			print(f"{index}、{name}")
		choice = input("请选择文章创作模型（输入序号）: ")
		try:
			choice = int(choice) - 1
			if 0 <= choice < len(self.generate_model_list):
				model = self.generate_model_list[choice]
				title_list = input("请输入文章标题，多个的话用‘|’分隔开:").split('|')
				create_articles(title_list, self.bot_list,model=model)

			else:
				print("无效的选项，请重新选择。")
		except ValueError:
			print("请输入一个有效的数字序号。")

	def manage_tasks(self):
		"""处理任务管理选项"""
		lever_2 = int(input("""
-31、为所有用户上传VIP文档
-32、为单个用户上传VIP文档
-33、自动化原力任务（开发测试中....）
-34、删除未通过的文档
-99、返回
请输入对应的数字：
        """))

		if lever_2 == 31:
			self.upload_vip_docs_for_all_users()
		elif lever_2 == 32:
			self.upload_vip_docs_for_single_user()
		elif lever_2 == 33:
			self.automate_task()
		elif lever_2 == 34:
			self.delete_failed_docs()

	def upload_vip_docs_for_all_users(self):
		"""为每个用户上传VIP文档"""
		num = int(input("请填写要上传的文档数量："))
		is_headless = int(input("是否无界面？（1无界面、0打开浏览器）："))
		if num:
			for item in self.account_list:
				driver = BM(is_headless=is_headless, cookie=item["cookie"], target_type=1)
				print(f"选定账号：{item['uname']}")
				TE(driver.driver, folder_path="C:\\Users\\Administrator\\Desktop\\july\\doc_files\\vip_files",upload_limit=num, task_type=1)
				time.sleep(30)

	def upload_vip_docs_for_single_user(self):
		"""为单个用户上传VIP文档"""
		options = [(i + 1, account['uname']) for i, account in enumerate(self.account_list)]
		for index, name in options:
			print(f"{index}、{name}")
		choice = input("请选择要操作的账号（输入序号）: ")
		try:
			choice = int(choice) - 1
			if 0 <= choice < len(self.account_list):
				num = int(input("请填写要上传的文档数量："))
				if num:
					is_headless = int(input("是否无界面？（1无界面、0打开浏览器）："))
					driver = BM(is_headless=is_headless, cookie=self.account_list[choice]["cookie"], target_type=1)
					print(f"选定账号：{self.account_list[choice]['uname']}")
					TE(driver = driver.driver, folder_path="C:\\Users\\Administrator\\Desktop\\july\\doc_files\\vip_files",upload_limit=num,task_type=1)
			else:
				print("无效的选项，请重新选择。")
		except ValueError:
			print("请输入一个有效的数字序号。")

	def automate_task(self):
		"""自动化原力任务"""
		options = [(i + 1, account['uname']) for i, account in enumerate(self.account_list)]
		for index, name in options:
			print(f"{index}、{name}")
		choice = input("请选择要操作的账号（输入序号）: ")
		choice = int(choice) - 1
		if 0 <= choice < len(self.account_list):
			is_headless = int(input("是否无界面？（1无界面、0打开浏览器）："))
			driver = BM(is_headless=is_headless, cookie=self.account_list[choice]["cookie"], target_type=2)
			print(f"选定账号：{self.account_list[choice]['uname']}")
			TE(driver.driver, folder_path="C:\\Users\\Administrator\\Desktop\\july\\doc_files\\task_files",
			   upload_limit=50, task_type=2, ac=self.ac)
		else:
			print("无效的选项，请重新选择。")

	def delete_failed_docs(self):
		"""删除未通过的文档"""
		num = int(input("请填写要检查的页数（推荐5）："))
		if num:
			for item in self.account_list:
				print(f"选定账号：{item['uname']}")
				bc = BC(cookie_str=item["cookie"])
				print(bc.del_fail_article(total_page=num))
				time.sleep(10)

	# def login_manager(self):
	# 	"""添加登录账号"""
	#
	def main_menu(self):
		"""主菜单"""
		while True:
			lever_1 = int(input("""
1、账号管理
2、文章生成
3、任务管理
0、退出程序
请输入对应数字：
"""))
			if lever_1 == 0:
				break
			elif lever_1 == 1:
				self.account_management()
			elif lever_1 == 2:
				self.generate_articles()
			elif lever_1 == 3:
				self.manage_tasks()
			elif lever_1 == 186:
				add_account()


if __name__ == "__main__":
	# uid = int(input("请输入UID："))
	manager = WenkuManager()
	manager.main_menu()
